<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
 
/**
 * Script file of pmapi component
 */
class com_pmapiInstallerScript
{
        function install($parent) {}
        function uninstall($parent) {}
        function update($parent) {}
        function postflight($type, $parent) {} 
        
        
        /**
         * method to run before an install/update/uninstall method
         *
         * @return void
         */
        function preflight($type, $parent) 
        {
            $msg='';

            // Only allow to install on Joomla! 2.5.0 or later with PHP 5.3.0 or later
            if (!version_compare($v=JVERSION, '2.5.6', 'ge'))
                $msg .= "You need Joomla! 2.5.6 or later to install this component ($v found). ";
            
            if (!version_compare( $v= $this->_getPHPVersion(), '5.3.1', 'ge'))
                $msg .= "You need PHP 5.3.1 or later to install this component ($v found). ";
            
            if (!version_compare($v= $this->_getVirtuemartVersion(), '2.0.25', 'ge'))
                $msg .= "Virtuemart 2.0.25 or later needed ($v found). ";
            
            if ($msg) JError::raiseWarning(100, "<p>$msg</p>");
            
            return $msg?false:true;
        }
        
         
        private function _getVirtuemartVersion()
        {
            $db = JFactory::getDbo();
            $db->setQuery("SELECT enabled FROM #__extensions WHERE name = 'virtuemart' AND type='component'");
            $is_enabled = $db->loadResult();
            if ($is_enabled){
                if (version_compare(JVERSION, '3.0.0', 'ge')) {
                    $xml = JFactory::getXML(JPATH_SITE .'/components/com_virtuemart/virtuemart.xml');
                    $version = (string)$xml->version;      
                } else {
                    $parser = JFactory::getXMLParser('Simple');
                    $xml = JPATH_ADMINISTRATOR .'/components/com_virtuemart/virtuemart.xml';
                    $parser->loadFile($xml);
                    $doc = $parser->document;
                    $element = $doc->getElementByPath('version');
                    $version = $element->data();    
                }
            } else {
                $version = '0.0.0'; // all bets are off!
            }
            
            return $version;
        }

 
        private function _getPHPVersion()
        {         
            if (defined('PHP_VERSION')){
                $version = PHP_VERSION;
            }elseif (function_exists('phpversion')){
                $version = phpversion();
            }else{
                $version = '5.0.0'; // all bets are off!
            }

            return $version;
        }


}